import DB from '@/utils/sqlite.js';
import { formatDate, buildWhereClause, sortByDate, safeFixed, safeLocaleString } from '@/utils/common.js';

/**
 * 计算每条记录的相关数据（油耗、行驶里程、每公里油费、优惠金额等）
 * 
 * @param {Array} filteredRecords - 过滤后的记录列表（仅包含需要计算的记录）
 * @param {Array} allRecords - 所有记录列表（用于辅助计算，如前一条记录的里程）
 * @returns {Array} 处理后的记录列表
 */
const calculateOneRecord = (filteredRecords, allRecords) => {
  // 确保所有记录按日期排序
  const sortedAllRecords = sortByDate([...allRecords]);

  return filteredRecords.map(record => {
    // 查找当前记录在完整列表中的索引
    const index = sortedAllRecords.findIndex(r => r.id === record.id);
    const prevRecord = index > 0 ? sortedAllRecords[index - 1] : null;

    // 计算油耗（升/百公里）
    let mileage = 0;
    if (prevRecord) {
      mileage = record.mileage - prevRecord.mileage;
    }
    const fuelEconomy = mileage > 0 ? (record.liters / mileage) * 100 : 0;

    // 计算本次行驶里程
    let tripMileage = 0;
    if (prevRecord) {
      tripMileage = record.mileage - prevRecord.mileage;
      if (tripMileage < 0) tripMileage = 0;
    }

    // 计算每公里油费
    let costPerKm = 0;
    if (prevRecord && record.actual_amount && tripMileage > 0) {
      costPerKm = (record.actual_amount || 0) / tripMileage;
    }

    // 计算优惠金额
    const discountAmount = (record.oil_pump_amount || 0) - (record.actual_amount || 0);

    return {
      id: record.id,
      car_id: record.car_id,
      date: formatDate(record.date),
      is_full: record.is_full,
      liters: record.liters ? record.liters.toFixed(2) : '0.00',
      actual_amount: record.actual_amount ? record.actual_amount.toFixed(2) : '0.00',
      oil_pump_amount: record.oil_pump_amount ? record.oil_pump_amount.toFixed(2) : '0.00',
      price_per_liter: record.price_per_liter ? record.price_per_liter.toFixed(2) : '0.00',
      mileage: record.mileage.toLocaleString(),
      fuelEconomy: fuelEconomy.toFixed(1),
      fuelEconomyColor: fuelEconomy >= 10 ? 'bad' : 'good',
      tripMileage: tripMileage.toFixed(0),
      costPerKm: costPerKm.toFixed(2),
      discountAmount: (discountAmount > 0 ? discountAmount : 0).toFixed(2)
    };
  });
};

/**
 * 计算全部记录的相关数据（总费用、综合油耗、总里程、综合每公里油费）
 * 
 * @param {Array} records - 加油记录列表
 * @returns {Object} 包含总费用、综合油耗、总里程、综合每公里油费的对象
 */
const calculateAllRecord = (records) => {
  // 计算总费用
  let fuelTotalCosts = 0
  if (records.length) {
    fuelTotalCosts = records.reduce((sum, record) => {
      return sum + (record.actual_amount || 0)
    }, 0)
  }

  // 计算总里程和综合油耗
  let fuelTotalFuelEconomy = 0
  let fuelTotalMileage = 0

  if (records.length) {
    // 找到记录中里程最小和最大的记录
    const sortedRecords = [...records].sort((a, b) => a.mileage - b.mileage)
    const firstRecord = sortedRecords[0]
    const lastRecord = sortedRecords[sortedRecords.length - 1]

    // 计算总里程
    fuelTotalMileage = lastRecord.mileage - firstRecord.mileage

    // 计算综合油耗
    if (records.length >= 2 && fuelTotalMileage > 0) {
      // 计算总油量
      const fuelTotalLiters = records.reduce((sum, record) => {
        return sum + (record.liters || 0)
      }, 0)

      // 计算综合油耗
      fuelTotalFuelEconomy = (fuelTotalLiters / fuelTotalMileage) * 100
    }
  }

  // 计算总加油量
  const fuelTotalLiters = records.reduce((sum, record) => {
    return sum + (record.liters || 0)
  }, 0)

  return {
    fuelTotalCosts: safeFixed(fuelTotalCosts),
    fuelTotalFuelEconomy: safeFixed(fuelTotalFuelEconomy, 1),
    fuelTotalMileage: safeLocaleString(fuelTotalMileage),
    fuelTotalLiters: safeFixed(fuelTotalLiters),
    fuelTotalCostPerKm: safeFixed(fuelTotalMileage > 0 ? fuelTotalCosts / fuelTotalMileage : 0, 2)
  }
};

/**
 * 获取加油记录列表
 * 
 * @param {number} carId - 车辆ID
 * @param {string|number} year - 年份筛选，默认为'全部'
 * @returns {Promise<Object>} 包含记录列表和统计数据的对象
 */
export const getFuelRecords = async (carId, year = '全部') => {
  try {
    const where = buildWhereClause(carId, year);

    // 并行获取数据以提高性能
    const [records, allRecords] = await Promise.all([
      DB.getList('fuel_records', where, {}, 'date DESC'),
      DB.getList('fuel_records', { car_id: carId }, {}, 'date DESC')
    ]);

    // 按日期排序
    const sortedRecords = sortByDate(records);

    // 计算每条记录的相关数据（油耗、行驶里程、每公里油费、优惠金额等）
    const fuelRecords = calculateOneRecord(sortedRecords, allRecords);

    // 计算全部记录的相关数据（总费用、综合油耗、总里程、每公里油费）
    const fuelStatistics = calculateAllRecord(sortedRecords);

    // 返回包含记录列表和统计数据的对象
    return {
      fuelRecords: fuelRecords,
      fuelStatistics: fuelStatistics
    };
  } catch (error) {
    console.error('获取加油记录失败:', error);
    return {
      fuelRecords: [],
      fuelStatistics: {
        fuelTotalCosts: '0.00',
        fuelTotalFuelEconomy: '0.0',
        fuelTotalMileage: '0',
        fuelTotalLiters: '0.00',
        fuelTotalCostPerKm: '0.00'
      }
    };
  }
};

/**
 * 根据ID获取加油记录
 * 
 * @param {number} id - 记录ID
 * @returns {Promise<Object>} 加油记录数据
 */
export const getFuelRecordById = async (id) => {
  try {
    const record = await DB.getOneById('fuel_records', id);
    if (record) {
      // 对获取到的记录进行格式化处理
      return {
        id: record.id,
        car_id: record.car_id,
        date: formatDate(record.date),
        is_full: record.is_full,
        liters: record.liters ? record.liters.toFixed(2) : '0.00',
        actual_amount: record.actual_amount ? record.actual_amount.toFixed(2) : '0.00',
        oil_pump_amount: record.oil_pump_amount ? record.oil_pump_amount.toFixed(2) : '0.00',
        price_per_liter: record.price_per_liter ? record.price_per_liter.toFixed(2) : '0.00',
        mileage: record.mileage.toLocaleString()
      };
    }
    return null;
  } catch (error) {
    console.error('获取加油记录失败:', error);
    throw error;
  }
};

/**
 * 添加加油记录
 * 
 * @param {Object} record - 加油记录数据
 * @returns {Promise<boolean>} 是否添加成功
 */
export const addFuelRecord = async (record) => {
  try {
    await DB.save('fuel_records', record);
    return true;
  } catch (error) {
    console.error('添加加油记录失败:', error);
    return false;
  }
};

/**
 * 更新加油记录
 * 
 * @param {number} id - 记录ID
 * @param {Object} record - 要更新的记录数据
 * @returns {Promise<boolean>} 是否更新成功
 */
export const updateFuelRecord = async (id, record) => {
  try {
    await DB.updateById('fuel_records', record, id);
    return true;
  } catch (error) {
    console.error('更新加油记录失败:', error);
    return false;
  }
};

/**
 * 删除加油记录
 * 
 * @param {number} id - 记录ID
 * @returns {Promise<boolean>} 是否删除成功
 */
export const deleteFuelRecord = async (id) => {
  try {
    await DB.deleteById('fuel_records', id);
    return true;
  } catch (error) {
    console.error('删除加油记录失败:', error);
    return false;
  }
};